import config from './config.js'

/**
   * 检查session_key是否过期
   * @return true-未过期；false-已过期
   */
function checkSession() {
  return new Promise((resolve, reject) => {
    wx.checkSession({
      success: () => {
        resolve(true)
      },
      fail: () => {
        resolve(false)
      }
    })
  })
}

/**
 * 微信登录
 */
function wxLogin() {
  return new Promise((resolve, reject) => {
    wx.login({
      success: res => {
        resolve(res.code)
      },
      fail: err => {
        reject(err)
      }
    })
  })
}

/**
 * 服务器登录
 */
function authLogin(form) {
  return new Promise((resolve, reject) => {
    resolve('8s7df68s76fes')
    // request.get(`/api/weChatMini/v1/user/${config.wxAppId}/login`, form).then(res => {
    //   if (res.data.token) {
    //     wx.setStorageSync('token', res.data.token)
    //     wx.setStorageSync('userType', res.data.userType)
    //     wx.setStorageSync('userId', res.data.userId)
    //     resolve(res.data.weChatMiniOpenId)
    //   } else {
    //     resolve(res.data)
    //   }
    // }).catch(err => {
    //   reject(err)
    // })
  })
}

async function login(data) {
  // wx.showLoading()
  let openId = wx.getStorageSync('openid')
  let token = wx.getStorageSync('token')
  const isExpired = await checkSession()
  if (!openId || !isExpired || !token) {
    console.info('%c====重新登录====', 'color:blue')
    const code = await wxLogin()
    const form = {
      code: code
    }
    if (data.referrerId) {
      form.referrerId = data.referrerId
    }
    try {
      openId = await authLogin(form)
      wx.setStorageSync('openid', openId)
    } catch(e) {
      throw new Error(e)
    }
  }
  // wx.hideLoading()
  return openId
}

export default login